package com.gl.goods.net;

import android.content.Intent;
import android.util.Log;

import com.gl.goods.base.BaseBean;
import com.gl.goods.base.ErrorMessageBean;
import com.gl.goods.base.MyApplication;
import com.gl.goods.net.converter.GsonConverterFactory;
import com.gl.goods.ui.login.activity.LoginActivity;
import com.gl.library.tool.RxSPTool;
import com.gl.library.tool.RxTool;
import com.gl.library.utils.CommUtils;
import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

/**
 * Retrofit请求工具类
 * Created by wangwc on 2016/12/16.
 */
public class RetrofitClient {
    private ApiService apiService;
    private static volatile RetrofitClient instance;

    class HttpCacheInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if (!CommUtils.isNetworkAvailable(MyApplication.getAppContext())) {
                request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
                Log.d("Okhttp", "no network");
            }

            Response originalResponse = chain.proceed(request);
            if (CommUtils.isNetworkAvailable(MyApplication.getAppContext())) {
                //有网的时候读接口上的@Headers里的配置，你可以在这里进行统一的设置
                String cacheControl = request.cacheControl().toString();
                return originalResponse.newBuilder()
                        .header("Cache-Control", cacheControl)
                        .removeHeader("Pragma")
                        .build();
            } else {
                return originalResponse.newBuilder()
                        .header("Cache-Control", "public, only-if-cached, max-stale=2419200")
                        .removeHeader("Pragma")
                        .build();
            }
        }
    }
    public static RetrofitClient getInstance() {
        if (instance == null) {
            synchronized (RetrofitClient.class) {
                if (instance == null) {
                    instance = new RetrofitClient();
                }
            }
        }
        return instance;
    }

    /**
     * 设置Header
     *
     * @return
     */
    private Interceptor getHeaderInterceptor() {
        return new Interceptor() {
            @Override
            public Response intercept( Chain chain) throws IOException {
                Request original = chain.request();
                String loginToken = RxSPTool.getString(MyApplication.getContext(),"token");
                Request.Builder requestBuilder = original.newBuilder()
                        //添加Token
                        .header("Authorization", loginToken);
                Request request = requestBuilder.build();
                return chain.proceed(request);
            }
        };

    }
    private Interceptor responseInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response response = chain.proceed(chain.request());
            if (response.body() != null) {
                String json = response.body().string().replace("\"data\":null", "\"data\":{}");
                ResponseBody body = ResponseBody.create(response.body().contentType(), json);
                Gson gson = new Gson();
                BaseBean bean = gson.fromJson(body.string(), BaseBean.class);
                if (bean.getCode() == -1){
                    MyApplication.getInstance().logout();
                    RxSPTool.putInt(RxTool.getContext(), "memberId", 0);
                    RxSPTool.putString(RxTool.getContext(), "token", "");
                    Intent i = new Intent(RxTool.getContext(), LoginActivity.class);
                    RxTool.getContext().startActivity(i);
                }
                return response.newBuilder().body(body).build();
            }
            return response;
        }
    };

    /**
     * 设置拦截器
     *
     * @return
     */
    private Interceptor getInterceptor() {

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        //显示日志
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        return interceptor;
    }

    public ApiService getApi(String baseUrl) {
        //初始化一个client,不然retrofit会自己默认添加一个
        OkHttpClient client = new OkHttpClient().newBuilder()
                //设置Header
                .addInterceptor(getHeaderInterceptor())
                //设置拦截器
                .addInterceptor(getInterceptor())
//                .addInterceptor(responseInterceptor)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .client(client)
                //设置网络请求的Url地址
                .baseUrl(baseUrl)
                //设置数据解析器
                .addConverterFactory(GsonConverterFactory.create())
                //设置网络请求适配器，使其支持RxJava与RxAndroid
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        //创建—— 网络请求接口—— 实例
        apiService = retrofit.create(ApiService.class);
        return apiService;
    }
}